package com.fox.xn.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fox.xn.model.Answer;
import com.fox.xn.model.AnswerItem;
import com.fox.xn.service.PollService;
import com.fox.xn.vo.Result;

@Controller
public class XnController {
	@Autowired
	PollService ps;
	
	@RequestMapping("/")
	public String index(){
		return "index";
	}
	@RequestMapping("/doit")
	@ResponseBody
	public Result  doit(HttpServletRequest request){
		Result r = new Result();
		Answer an = new Answer();
		an.setDoAt(new Date());
		an.setUa(request.getHeader("User-Agent"));
		an.setIp(getClientIP(request));
		List<AnswerItem> items = new ArrayList<>();
		request.getParameterMap().keySet().stream().forEach(e->{
			AnswerItem ai = new AnswerItem();
			ai.setAnswer(Integer.parseInt(request.getParameter(e)));
			ai.setQuestion(Integer.parseInt(e));
			items.add(ai);
		});;
		ps.doit(an, items);
		return r;
	}
	
	private String getClientIP(HttpServletRequest request){
		String ipAddress  = request.getHeader("X-FORWARDED-FOR");
		if(ipAddress == null)
		{
		  ipAddress = request.getRemoteAddr();
		}
		return ipAddress;
	}
}
